using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using Avalonia.Input.Platform;
using System;
using System.Linq;
using System.Threading.Tasks;
using AvaAI批量点评系统.ViewModels;
using AvaAI批量点评系统.Services;
using System.Diagnostics;
using System.IO;
using Avalonia.Data.Converters;
using System.Globalization;
using System.Collections.Generic;
using System.ComponentModel;

namespace AvaAI批量点评系统.Views;

public partial class MainView : UserControl
{
    private readonly CameraService _cameraService;
    private CommentPreviewView? _previewView;

    public MainView()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;
        _cameraService = new CameraService();
    }

    private void OnDataContextChanged(object? sender, EventArgs e)
    {
        if (DataContext is MainViewModel viewModel)
        {
            // 监听ShowPreviewView属性变化
            viewModel.PropertyChanged += OnViewModelPropertyChanged;
        }
    }

    private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(MainViewModel.ShowPreviewView) &&
            DataContext is MainViewModel viewModel)
        {
            if (viewModel.ShowPreviewView)
            {
                ShowPreviewView(viewModel);
            }
            else
            {
                HidePreviewView();
            }
        }
    }

    private void ShowPreviewView(MainViewModel mainViewModel)
    {
        if (_previewView == null)
        {
            _previewView = new CommentPreviewView();
        }

        // 加载数据到预览界面
        if (_previewView.ViewModel != null && mainViewModel.LastGeneratedComments.Count > 0)
        {
            var courseName = mainViewModel.SelectedSubject != "未识别" ? mainViewModel.SelectedSubject : "默认课程";
            var grade = mainViewModel.StartGrade != "未识别" ? mainViewModel.StartGrade : "三年级";
            var difficulty = mainViewModel.Difficulty != "未识别" ? mainViewModel.Difficulty : "入门";

            _previewView.ViewModel.LoadStudentComments(
                mainViewModel.LastGeneratedComments,
                courseName,
                grade,
                difficulty
            );
        }

        // 将预览界面设置到ContentControl中
        var previewContentControl = this.FindControl<ContentControl>("PreviewContentControl");
        if (previewContentControl != null)
        {
            previewContentControl.Content = _previewView;
        }
    }

    private void HidePreviewView()
    {
        var previewContentControl = this.FindControl<ContentControl>("PreviewContentControl");
        if (previewContentControl != null)
        {
            previewContentControl.Content = null;
        }
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);
        // 界面加载完成后的初始化操作
    }

    // 导航到指定区域
    private void OnNavigateToSection(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag?.ToString() is string sectionName)
        {
            ScrollToSection(sectionName);
        }
    }

    private void ScrollToSection(string sectionName)
    {
        var sectionElement = sectionName switch
        {
            "batch" => this.FindControl<Border>("BatchSection"),
            "expand" => this.FindControl<Border>("ExpandSection"),
            "image" => this.FindControl<Border>("ImageSection"),
            "course" => this.FindControl<Border>("CourseIntroductionSection"),
            "result" => this.FindControl<Border>("ResultSection"),
            _ => null
        };

        if (sectionElement != null)
        {
            sectionElement.BringIntoView();
        }
    }

    // 摄像头拍照功能
    private async void OnCameraClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not MainViewModel viewModel) return;

        try
        {
            viewModel.IsProcessing = true;
            viewModel.OutputResult = "🔍 正在检查摄像头设备...";

            // 检查摄像头是否可用
            var cameraAvailable = await _cameraService.IsCameraAvailableAsync();
            if (!cameraAvailable)
            {
                viewModel.OutputResult = "❌ 未检测到可用的摄像头设备\n\n建议：\n1. 请检查摄像头是否正确连接\n2. 确认摄像头权限已开启\n3. 尝试重新连接摄像头\n4. 或使用'选择本地图片'功能";
                return;
            }

            viewModel.OutputResult = "📸 摄像头设备检测成功！正在启动拍照功能...\n\n请在摄像头应用中完成拍照，系统将自动检测新拍摄的照片。";

            // 清理旧的临时文件
            _cameraService.CleanupTempFiles();

            // 执行拍照
            var imagePath = await _cameraService.CapturePhotoAsync();
            
            if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
            {
                viewModel.SelectedImagePath = imagePath;
                var fileInfo = new FileInfo(imagePath);
                var fileSizeKB = fileInfo.Length / 1024;
                
                viewModel.OutputResult = $"✅ 摄像头拍照成功！\n\n" +
                                       $"📸 图片已保存到: {imagePath}\n" +
                                       $"📊 文件大小: {fileSizeKB} KB\n" +
                                       $"🕒 拍摄时间: {fileInfo.CreationTime:yyyy-MM-dd HH:mm:ss}\n\n" +
                                       $"💡 您现在可以点击下方的'开始分析图片'按钮进行AI识别。";
            }
            else
            {
                viewModel.OutputResult = "❌ 摄像头拍照失败或已取消\n\n可能的原因：\n" +
                                       "• 用户取消了拍照操作\n" +
                                       "• 摄像头应用运行异常\n" +
                                       "• 文件保存失败\n\n" +
                                       "💡 您可以重试拍照或使用'选择本地图片'功能。";
            }
        }
        catch (Exception ex)
        {
            viewModel.OutputResult = $"❌ 摄像头功能启动失败: {ex.Message}\n\n建议：\n" +
                                   "1. 请检查摄像头是否正确连接和工作\n" +
                                   "2. 确认应用程序有摄像头访问权限\n" +
                                   "3. 检查系统摄像头驱动是否正常\n" +
                                   "4. 尝试关闭其他可能占用摄像头的应用程序\n" +
                                   "5. 或使用'选择本地图片'功能作为替代方案";
        }
        finally
        {
            viewModel.IsProcessing = false;
        }
    }

    private async void OnSelectExcelFileClick(object sender, RoutedEventArgs e)
    {
        if (DataContext is not MainViewModel viewModel) return;

        var filePath = await SelectExcelFileAsync();
        if (!string.IsNullOrEmpty(filePath))
        {
            viewModel.SelectedExcelPath = filePath;
            viewModel.OutputResult = $"已选择Excel文件: {System.IO.Path.GetFileName(filePath)}\n路径: {filePath}";
        }
    }

    private async void OnSelectImageClick(object sender, RoutedEventArgs e)
    {
        if (DataContext is not MainViewModel viewModel) return;

        var filePath = await SelectImageFileAsync();
        if (!string.IsNullOrEmpty(filePath))
        {
            viewModel.SelectedImagePath = filePath;
            viewModel.OutputResult = $"已选择图片文件: {System.IO.Path.GetFileName(filePath)}\n路径: {filePath}";
        }
    }

    public async Task<string?> SelectExcelFileAsync()
    {
        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel == null) return null;

        var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
        {
            Title = "选择Excel文件",
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType("Excel文件")
                {
                    Patterns = new[] { "*.xlsx", "*.xls" },
                    MimeTypes = new[] { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel" }
                },
                new FilePickerFileType("所有文件")
                {
                    Patterns = new[] { "*.*" }
                }
            }
        });

        if (files.Count > 0)
        {
            return files[0].Path.LocalPath;
        }

        return null;
    }

    public async Task<string?> SelectImageFileAsync()
    {
        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel == null) return null;

        var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
        {
            Title = "选择图片文件",
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType("图片文件")
                {
                    Patterns = new[] { "*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif", "*.webp" },
                    MimeTypes = new[] { "image/jpeg", "image/png", "image/bmp", "image/gif", "image/webp" }
                },
                new FilePickerFileType("所有文件")
                {
                    Patterns = new[] { "*.*" }
                }
            }
        });

        if (files.Count > 0)
        {
            return files[0].Path.LocalPath;
        }

        return null;
    }

    // 复制评语到剪贴板
    private async void OnCopyCommentClick(object sender, RoutedEventArgs e)
    {
        if (DataContext is not MainViewModel viewModel) return;

        try
        {
            var generatedComment = viewModel.GeneratedComment;
            if (string.IsNullOrWhiteSpace(generatedComment))
            {
                viewModel.OutputResult = "没有可复制的评语内容";
                return;
            }

            // 获取剪贴板服务
            var topLevel = TopLevel.GetTopLevel(this);
            if (topLevel?.Clipboard != null)
            {
                await topLevel.Clipboard.SetTextAsync(generatedComment);
                viewModel.OutputResult = $"📋 评语已成功复制到剪贴板！\n\n" +
                                       $"复制的内容：\n{generatedComment}\n\n" +
                                       "💡 您现在可以在任何地方使用 Ctrl+V 粘贴使用。";
            }
            else
            {
                viewModel.OutputResult = $"📋 评语内容（请手动复制）：\n\n" +
                                       $"===========================================\n" +
                                       $"{generatedComment}\n" +
                                       $"===========================================\n\n" +
                                       "💡 无法访问系统剪贴板，请手动选择复制以上内容。";
            }
        }
        catch (Exception ex)
        {
            if (DataContext is MainViewModel vm)
            {
                vm.OutputResult = $"📋 复制到剪贴板失败，请手动复制以下内容：\n\n" +
                                $"===========================================\n" +
                                $"{vm.GeneratedComment}\n" +
                                $"===========================================\n\n" +
                                $"错误信息: {ex.Message}";
            }
        }
    }
}

// 进度条宽度转换器
public class PercentageToWidthConverter : IMultiValueConverter
{
    public object Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
    {
        if (values.Count == 2 && 
            values[0] is double percentage && 
            values[1] is double containerWidth)
        {
            // 将百分比转换为实际宽度
            var width = containerWidth * (percentage / 100.0);
            return Math.Max(0, Math.Min(width, containerWidth));
        }
        
        return 0.0;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}